import Field from "../utils/Field";

export default class Session {

   constructor() { }

   executeSQL(sql: string, params: any): any {
      return "No Engine Support executeSQL Method";
   }

   async query(sql: string, ...params: any[]) {
      return this.executeSQL(sql, params);
   }

   async queryWith(sql: string, entity: any, ...params: any[]) {
      if ((typeof entity) != "function") {
         throw new Error('entity parameter error! expected function')
      } else {
         let name = entity.__proto__.name
         if (name != "Entity") {
            throw new Error('entity parameter is Entity subclass')
         }
      }
      let msg = await this.executeSQL(sql, params);
      let list = [];
      let msgList = msg || [];
      msgList.forEach(function (one) {
         let _entity = new entity();
         let _fields: Field[] = _entity['fields'];
         _fields.forEach(function (item) {
            _entity['__dirty__']['__' + item.propertyKey] = _entity[item.propertyKey] = one[item.field];
         })
         list.push(_entity);
      })

      return list;
   }

   async queryOne(sql: string, ...params: any[]) {
      let msg = await this.executeSQL(sql, params);
      return (msg && msg.length > 0) ? msg[0] : null;
   }

   async queryOneWith(sql: string, entity: any, ...params: any[]) {

      if ((typeof entity) != "function") {
         throw new Error('entity parameter error! expected function')
      } else {
         let name = entity.__proto__.name
         if (name != "Entity") {
            throw new Error('entity parameter is Entity subclass')
         }
      }
      let one = await this.queryOne(sql, params);
      let _entity = new entity();
      let _fields: Field[] = _entity['fields'];
      _fields.forEach(function (item) {
         _entity['__dirty__']['__' + item.propertyKey] = _entity[item.propertyKey] = one[item.field];
      })
      return _entity
   }

   async delete(sql: string, ...params: any[]) {
      return this.executeSQL(sql, params);
   }

   async update(sql: string, ...params: any[]) {
      return this.executeSQL(sql, params);
   }

   async create(sql: string, ...params: any[]) {
      return this.executeSQL(sql, params);
   }
}